package com.ljfiction.book.activitys;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.ljfiction.book.Dialog.LoadingDIalog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.city.JsonBean;
import com.ljfiction.book.city.JsonFileReader;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.SoftHideKeyBoardUtil;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.IDCardValidate;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.TimeTool;
import com.ljfiction.book.tools.Tool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class ApplyAuthorActivity extends BaseActivity {

    @BindView(R.id.back_apply_author)
    ImageView backApplyAuthor;
    @BindView(R.id.myname)
    ContainsEmojiEditText myname;

    @BindView(R.id.identitycard)
    ContainsEmojiEditText identitycard;
    @BindView(R.id.qqnum)
    ContainsEmojiEditText qqnum;
    @BindView(R.id.email)
    ContainsEmojiEditText email;

    @BindView(R.id.site)
    TextView site;
    @BindView(R.id.sityselect)
    LinearLayout sityselect;
    @BindView(R.id.apply_for_auther)
    SuperButton applyForAuther;
    @BindView(R.id.siteview)
    TextView siteview;
    @BindView(R.id.toptext)
    TextView toptext;
    @BindView(R.id.scrollviewapply)
    HorizontalScrollView scrollviewapply;
    @BindView(R.id.tonext)
    SuperButton tonext;
    @BindView(R.id.name_my)
    ContainsEmojiEditText nameMy;
    @BindView(R.id.phonenum)
    TextView phonenum;
    @BindView(R.id.xiangxidizhi)
    ContainsEmojiEditText xiangxidizhi;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_author);
        ButterKnife.bind(this);
        SoftHideKeyBoardUtil.assistActivity(this);
        initJsonData();
        nameMy.setHint(UserManageBean.userBean.getPseudonym() + "(昵称既是笔名，此处可修改一次)");
        phonenum.setText(UserManageBean.userBean.getUserPhone());
        scrollviewapply.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
    }

    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String text = options1Items.get(options1).getPickerViewText() + "," +
                        options2Items.get(options1).get(options2) + "," +
                        options3Items.get(options1).get(options2).get(options3);
                siteview.setText(text);
            }
        }).setTitleText("选择城市")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.GRAY)
                .setContentTextSize(18)
                .setOutSideCancelable(false)
                .setCancelText("取消")
                .setBgColor(0xffefefef)
                .setSubmitText("确定")
                .build();
          /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {   //解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //  获取json数据
        String JsonData = JsonFileReader.getJson(this, "province_data.json");
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return detail;
    }


    @OnClick({R.id.back_apply_author, R.id.sityselect, R.id.apply_for_auther, R.id.tonext})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_apply_author:
                if (scrollviewapply.getScrollX() > ScreenUtils.getNum(ApplyAuthorActivity.this,100)) {
                    scrollviewapply.smoothScrollTo(0, ScreenUtils.getNum(ApplyAuthorActivity.this,80));
                    toptext.setText("联系方式");
                } else {
                    goBack();
                }
                break;
            case R.id.sityselect:
                InputMethodManager imm =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                if(imm != null) {
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                            0);
                }
                showPickerView();
                break;
            case R.id.tonext:
                if (qqnum.getText().toString().equals("")) {
                    showToast("请填写真实qq号");
                } else if (!StringTool.isEmailtow(email.getText().toString())){
                    showToast("请填写正确邮箱");
                }else if ("".equals(siteview.getText().toString())){
                    showToast("请选择地址");
                }else if ("".equals(xiangxidizhi.getText().toString())){
                    showToast("请填写详细地址");
                }else {
                    Tool.hideKeybard(ApplyAuthorActivity.this);
                    scrollviewapply.smoothScrollTo(ScreenUtils.getScreenWidth(), ScreenUtils.getNum(ApplyAuthorActivity.this,80));
                    toptext.setText("上传个人资料");
                }
                break;
            case R.id.apply_for_auther:
                if (myname.getText().toString().equals("") || !StringTool.isChina(myname.getText().toString())) {
                    showToast("请输入真实姓名");
                    return;
                } else if (identitycard.getText().toString().equals("")) {
                    showToast("请填写身份证号");
                    return;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !IDCardValidate.validate_effective(identitycard.getText().toString())) {
                    showToast("请填写真实身份证号");
                    return;
                } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N && !StringTool.isIdCard(identitycard.getText().toString())) {
                    showToast("请填写真实身份证号");
                    return;
                } else if (qqnum.getText().toString().equals("")) {
                    showToast("请填写真实qq号");
                    return;
                } else if (!nameMy.getText().toString().equals("") && !StringTool.verifyUserName(nameMy.getText().toString())) {
                    showToast("昵称只支持汉字、字母、数字和下划线");
                    return;
                } else {
                    if (nameMy.getText().toString().equals("")) {
                        nameMy.setText(UserManageBean.userBean.getPseudonym());
                    }else if(nameMy.getText().toString().length()>7){
                        showToast("亲，笔名不能超过7个字哦");
                        return;
                    }
                    if (UserManageBean.userBean.getPseudonym().equals(nameMy.getText().toString())){
                        toauthor();
                    }else {
                        toYanzhengName();
                    }

                }
                break;

        }
    }
    private NoBackgLodDialog loadingDialog;
    private void toYanzhengName() {
        OkHttpUtils.get(HttpManager.IP + "/person-checkNickName/" + nameMy.getText().toString())

                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (loadingDialog == null) {
                            loadingDialog = new NoBackgLodDialog(ApplyAuthorActivity.this, true);
                        }
                        loadingDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if ("200".equals(jsonObject.getString("returnCode"))) {
                                toauthor();
                            } else if ("500".equals(jsonObject.getString("returnCode"))) {
                                loadingDialog.dismis();
                                showToast(jsonObject.getString("msg"));
                            } else {
                                loadingDialog.dismis();
                            }
                        } catch (JSONException e) {
                            loadingDialog.dismis();
                            e.printStackTrace();
                        }
                    }
                });
    }
    private void toauthor() {
        OkHttpUtils.post(HttpManager.IP + "/person-applicantAuthor")

                .params("pseudonym", nameMy.getText().toString())
                .params("realName", myname.getText().toString())
                .params("userPhone", phonenum.getText().toString())
                .params("userQQ", qqnum.getText().toString())
                .params("userAddress", siteview.getText().toString()+xiangxidizhi.getText().toString())
                .params("userBorndate", TimeTool.getCurrenttime())
                .params("userEmail", email.getText().toString())
                .params("userIdentityCard", identitycard.getText().toString())
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (loadingDialog == null) {
                            loadingDialog = new NoBackgLodDialog(ApplyAuthorActivity.this, true);
                        }
                        loadingDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        loadingDialog.dismis();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                showToast("注册成功");
                                setResult(1);
                                UserManageBean.backgroundLogin(ApplyAuthorActivity.this);
                                goBack();

                            } else {
                                if (jsonObject.getInt("returnCode") == 400){
                                    Intent intent =new Intent(ApplyAuthorActivity.this,LoginActivity.class);
                                    startActivity(intent);

                                }
                                showToast(jsonObject.getString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


}
